package ru.usu.gv.gui.behavior;

import com.sun.j3d.utils.behaviors.mouse.MouseBehavior;

import ru.usu.gv.uicomponents.UIEdge;

import javax.media.j3d.TransformGroup;
import javax.media.j3d.WakeupCriterion;
import javax.media.j3d.WakeupOnAWTEvent;
import javax.media.j3d.WakeupOr;

import java.awt.AWTEvent;
import java.awt.event.MouseEvent;
import java.util.Enumeration;

/**
 @author Sergey Pupyrev 
 21.01.2007
 
 TODO: check how it works
 */

public class DragEdgeMouseBehavior extends MouseBehavior
{
    private UIEdge edge;
    private boolean _enabled = true;

    public DragEdgeMouseBehavior(TransformGroup transformGroup)
    {
        super(transformGroup);
    }

    public void init(UIEdge edge, int x, int y)
    {
        this.edge = edge;
        setEnabledInternal(true);
        setEnable(true);
    }

    @Override
    public void initialize()
    {
        super.initialize();
        mouseEvents = new WakeupCriterion[2];

        mouseEvents[0] = new WakeupOnAWTEvent(MouseEvent.MOUSE_DRAGGED);
        mouseEvents[1] = new WakeupOnAWTEvent(MouseEvent.MOUSE_RELEASED);
        mouseCriterion = new WakeupOr(mouseEvents);
        wakeupOn(mouseCriterion);
    }

    @Override
    public void processStimulus(Enumeration criteria)
    {
        if (!isEnableInternal())
        {
            wakeupOn(mouseCriterion);
            return;
        }

        while (criteria.hasMoreElements())
        {
            WakeupCriterion wakeup = (WakeupCriterion)criteria.nextElement();
            if (wakeup instanceof WakeupOnAWTEvent)
            {
                AWTEvent[] events = ((WakeupOnAWTEvent)wakeup).getAWTEvent();
                if (events.length > 0)
                {
                    MouseEvent evt = (MouseEvent)events[events.length - 1];
                    if (evt.getID() == MouseEvent.MOUSE_RELEASED)
                    {
                        setEnabledInternal(false);
                    }
                    else if (evt.getID() == MouseEvent.MOUSE_DRAGGED && !evt.isMetaDown() && !evt.isAltDown())
                    {
                        doDragEdge(evt.getX(), evt.getY());
                    }
                }
            }
        }

        wakeupOn(mouseCriterion);
    }

    private void doDragEdge(int x, int y)
    {
        edge.moveToCanvasPosition(x, y);
    }

    private boolean isEnableInternal()
    {
        return _enabled;
    }

    private void setEnabledInternal(boolean _enabled)
    {
        this._enabled = _enabled;
    }
}
